package top.dreamix.ktor.plugin

import io.ktor.client.plugins.api.createClientPlugin
import kotlin.collections.MutableMap

object SavedCookies {
    val yiban: MutableMap<String, String> = mutableMapOf()
}
val SaveSetCookie = createClientPlugin("SaveSetCookie") {

    fun parseSetCookie(setCookieHeader: String): Pair<String, String>? {
        return setCookieHeader.split(';', ignoreCase = false, limit = 2)
            .firstOrNull()
            ?.trim()
            ?.split('=', ignoreCase = false, limit = 2)
            ?.takeIf { it.size == 2 }
            ?.let { Pair(it[0].trim(), it[1].trim()) }
    }

    onResponse { response ->
        response.headers.getAll("Set-Cookie")?.let { it ->
            it.forEach {
                val result = parseSetCookie(it)
                if (result != null) {
                    SavedCookies.yiban[result.first] = result.second
                }
            }
        }
    }
}
